<?php
namespace App\Lib\Consul;


/**
 * Class Service
 * @package App\Http\Lib
 */
class Service implements MetaInterface
{

    /**
     * 服务ID
     * @var string
     */
    private $id;

    /**
     * 服务元数据
     * @var array
     */
    private $metas=[];

    /**
     * 服务详情
     * @var array
     */
    private $data = [];

    public function __construct(array $service=[]){
        $this->data  = $service;
        $this->metas = $service['Meta'] ?? [];
        $this->id = $service['ID'] ?? '';
    }

    /**
     * @inheritDoc
     */
    public function getLimiterRate()
    {
        return isset($this->metas['LIMITER_RATE']) ? abs((int) $this->metas['LIMITER_RATE']) : 0;
    }

    /**
     * @inheritDoc
     */
    public function getLimiterMax()
    {
        return isset($this->metas['LIMITER_MAX']) ? abs((int) $this->metas['LIMITER_MAX']) : 0;
    }

    /**
     * @inheritDoc
     */
    public function getServiceAddress()
    {
        return $this->data['Address']??($this->metas['SERVICE_ADDRESS']??'');
    }

    /**
     * @inheritDoc
     */
    public function getServicePort()
    {
        return $this->data['Port']??($this->metas['SERVICE_PORT']??0);
    }

    /**
     * @inheritDoc
     */
    public function getValidateActions()
    {
        return isset($this->metas['VALIDATE_ACTIONS']) ? explode(',', $this->metas['VALIDATE_ACTIONS']) : [];
    }

    /**
     * @inheritDoc
     */
    public function getNamespace(): string
    {
        return isset($this->metas['SERVICE_NAMESPACE']) ? str_replace('.', "\\", $this->metas['SERVICE_NAMESPACE']) : "App\\Rpc\\Lib";
    }

    /**
     * 是否需要验证
     * @param string $action
     * @return bool
     */
    public function needValid(string $action): bool{
        $actions = $this->getValidateActions();
        return in_array('all', $actions) || in_array($action, $actions) ? true : false;
    }


    /**
     * 是否需要限速
     * @inheritDoc
     */
    public function needLimit(): bool
    {
        $reta = $this->getLimiterRate();
        $max = $this->getLimiterMax();
        return ($reta > 0 && $max > 0 && $max >= $reta) ? true : false;
    }

    /**
     * 服务是否可用
     * @return bool
     */
    public function useful(){
        $address = $this->getServiceAddress();
        $port = $this->getServicePort();
        return (!empty($address) && !empty($port)) ? true : false;
    }

    /**
     * @return array
     */
    public function getData(){
        return $this->data;
    }

    /**
     * @return string
     */
    public function getId(): string
    {
        return $this->id;
    }

    /**
     * 获取HOST
     * @return string
     */
    public function getHost(): string
    {
        return 'tcp://' . $this->getServiceAddress().':' . $this->getServicePort();
    }


}
